<template>
  <div class="artist-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>歌手管理</span>
          <el-button type="primary" @click="handleCreate">新增歌手</el-button>
        </div>
      </template>

      <!-- Search Form -->
      <el-form :model="searchForm" inline>
        <el-form-item label="歌手名称">
          <el-input v-model="searchForm.artistName" placeholder="请输入歌手名称" clearable />
        </el-form-item>
        <el-form-item label="国家/地区">
          <el-input v-model="searchForm.country" placeholder="请输入国家/地区" clearable />
        </el-form-item>
        <el-form-item label="音乐风格">
          <el-select v-model="searchForm.genre" placeholder="请选择音乐风格" clearable>
            <el-option label="华语流行" value="华语流行" />
            <el-option label="摇滚" value="摇滚" />
            <el-option label="Pop" value="Pop" />
            <el-option label="Soul" value="Soul" />
            <el-option label="R&B" value="R&B" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- Artist Table -->
      <el-table
          :data="artistList"
          v-loading="loading"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="artistId" label="ID" width="80" />
        <el-table-column prop="artistName" label="歌手名称" width="150" />
        <el-table-column prop="artistNameEn" label="英文名" width="150" />
        <el-table-column label="头像" width="100">
          <template #default="{ row }">
            <el-image
                style="width: 60px; height: 60px"
                :src="row.avatarUrl"
                :preview-src-list="[row.avatarUrl]"
                fit="cover"
                hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="getGenderColor(row.gender)">
              {{ getGenderName(row.gender) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="country" label="国家/地区" width="120" />
        <el-table-column prop="birthDate" label="出生日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="debutDate" label="出道日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.debutDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="genre" label="音乐风格" width="150" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.artistId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

      <!-- Batch Actions -->
      <div class="batch-actions" v-if="selectedArtists.length > 0">
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <span class="selected-count">已选择 {{ selectedArtists.length }} 项</span>
      </div>
    </el-card>

    <!-- Artist Form Dialog -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        :close-on-click-modal="false"
        @closed="resetForm"
    >
      <el-form
          ref="artistFormRef"
          :model="artistForm"
          :rules="artistRules"
          label-width="100px"
          label-position="right"
      >
        <el-form-item label="歌手名称" prop="artistName">
          <el-input v-model="artistForm.artistName" placeholder="请输入歌手名称" />
        </el-form-item>
        <el-form-item label="英文名称" prop="artistNameEn">
          <el-input v-model="artistForm.artistNameEn" placeholder="请输入英文名称" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="artistForm.gender" placeholder="请选择性别">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
            <el-option label="组合" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="国家/地区" prop="country">
          <el-input v-model="artistForm.country" placeholder="请输入国家/地区" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
              v-model="artistForm.birthDate"
              type="date"
              placeholder="选择出生日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="出道日期" prop="debutDate">
          <el-date-picker
              v-model="artistForm.debutDate"
              type="date"
              placeholder="选择出道日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="artistForm.avatarUrl" placeholder="请输入头像URL" />
        </el-form-item>
        <el-form-item label="封面URL" prop="coverUrl">
          <el-input v-model="artistForm.coverUrl" placeholder="请输入封面URL" />
        </el-form-item>
        <el-form-item label="音乐风格" prop="genre">
          <el-input v-model="artistForm.genre" placeholder="请输入音乐风格，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input
              v-model="artistForm.introduction"
              type="textarea"
              :rows="3"
              placeholder="请输入歌手简介"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="artistForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../services/api'

// 数据状态
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增歌手')
const artistFormRef = ref(null)
const selectedArtists = ref([])

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  artistName: '',
  country: '',
  genre: '',
  status: ''
})

// 歌手表单
const artistForm = reactive({
  artistId: null,
  artistName: '',
  artistNameEn: '',
  gender: null,
  country: '',
  birthDate: '',
  debutDate: '',
  avatarUrl: '',
  coverUrl: '',
  genre: '',
  introduction: '',
  status: 1
})

// 表单验证规则
const artistRules = reactive({
  artistName: [
    { required: true, message: '请输入歌手名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  country: [
    { required: true, message: '请输入国家/地区', trigger: 'blur' }
  ]
})

// 歌手列表数据
const artistList = ref([])

// 生命周期钩子
onMounted(() => {
  fetchArtistList()
})

// 获取歌手列表
const fetchArtistList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }

    const response = await api.artistApi.getArtistManageList(params)

    if (response.code === 200) {
      // 处理后端返回的数据结构
      const data = response.data
      artistList.value = data.records || data.list || []

      // 处理分页信息
      pagination.total = data.total || 0

      // 如果后端没有返回分页信息，使用records数组长度
      if (!data.total && data.records) {
        pagination.total = data.records.length
      }
    } else {
      ElMessage.error(response.message || '获取歌手列表失败')
    }
  } catch (error) {
    console.error('获取歌手列表出错:', error)
    ElMessage.error('获取歌手列表出错')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  fetchArtistList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchArtistList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchArtistList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedArtists.value = selection.map(item => item.artistId)
}

// 打开创建对话框
const handleCreate = () => {
  dialogTitle.value = '新增歌手'
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑歌手'
  Object.keys(artistForm).forEach(key => {
    if (row[key] !== undefined) {
      artistForm[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await artistFormRef.value.validate()

    const formData = { ...artistForm }
    // 移除artistId如果是新增
    if (!formData.artistId) {
      delete formData.artistId
    }

    let response
    if (formData.artistId) {
      // 更新歌手
      response = await api.artistApi.updateArtist(formData.artistId, formData)
    } else {
      // 创建歌手
      response = await api.artistApi.createArtist(formData)
    }

    if (response.code === 200) {
      ElMessage.success(formData.artistId ? '更新歌手成功' : '创建歌手成功')
      dialogVisible.value = false
      fetchArtistList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('表单提交出错:', error)
    if (error instanceof Error) {
      ElMessage.error(error.message || '表单验证失败')
    }
  }
}

// 删除歌手
const handleDelete = (artistId) => {
  ElMessageBox.confirm('确认删除该歌手吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await api.artistApi.deleteArtist(artistId)
      if (response.code === 200) {
        ElMessage.success('删除歌手成功')
        fetchArtistList()
      } else {
        ElMessage.error(response.message || '删除歌手失败')
      }
    } catch (error) {
      console.error('删除歌手出错:', error)
      ElMessage.error('删除歌手出错')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 批量删除
const batchDelete = () => {
  if (selectedArtists.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }

  ElMessageBox.confirm(`确认删除选中的 ${selectedArtists.value.length} 个歌手吗?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await api.artistApi.batchDeleteArtists(selectedArtists.value)
      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        selectedArtists.value = []
        fetchArtistList()
      } else {
        ElMessage.error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除出错:', error)
      ElMessage.error('批量删除出错')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 重置表单
const resetForm = () => {
  artistFormRef.value?.resetFields()
  Object.keys(artistForm).forEach(key => {
    if (key === 'status') {
      artistForm[key] = 1
    } else if (key === 'gender') {
      artistForm[key] = null
    } else {
      artistForm[key] = ''
    }
  })
  artistForm.artistId = null
}

// 获取性别名称
const getGenderName = (gender) => {
  const genderMap = {
    1: '男',
    2: '女',
    3: '组合'
  }
  return genderMap[gender] || '未知'
}

// 获取性别颜色
const getGenderColor = (gender) => {
  const colorMap = {
    1: 'primary',
    2: 'danger',
    3: 'warning'
  }
  return colorMap[gender] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.artist-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.selected-count {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}
</style>